import React, { useEffect, useState, useRef, Ref } from 'react'
import type { MenuProps } from 'antd';
import type { InputRef } from 'antd';
import { Input, Button, List, Checkbox, Menu } from 'antd'
import './App.css'

const arr = Array(6).fill(null).map((v, i) => ({
  id:  Math.random(),
  content: `待办事项${i + 1}`,
  completed: false
}))
interface ItemType {
  id: number;
  content: string;
  completed: boolean;
}

const items: MenuProps['items'] = [
  {
    label: '全部',
    key: 'all',
  },
  {
    label: '已完成',
    key: 'completed',
  },
  {
    label: '未完成',
    key: 'uncompleted',
  }
]

type TimeoutHandle = ReturnType<typeof setTimeout>

const debounce = (fn: Function, delay: number) => {
  let timer: TimeoutHandle
  return (e: any) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn(e)
    }, delay)
  }
}

export default function App() {
  return (
    <>
      <TodoList />
    </>
  )
}

const TodoList = (props: any) => {
  const [list, setList] = useState<ItemType[]>([])
  const [current, setCurrent] = useState('all')
  const [showList, setShowList] = useState<ItemType[]>([])
  const [completedList, setCompletedList] = useState<ItemType[]>([])
  const [uncompletedList, setUncompletedList] = useState<ItemType[]>([])
  const [content, setContent] = useState('')
  const inputRef = useRef<InputRef>(null)

  useEffect(() => {
    setList(arr)
    setShowList(arr)
  }, [])

  // 切换菜单
  const menuChange: MenuProps['onClick'] = (e) => {
    console.log('切换菜单e.key: ', e.key);
    const completedList = list.filter(i=> i.completed===true)
    const uncompletedList = list.filter(i=> i.completed===false)
    setCurrent(e.key)
    switch (e.key) {
      case 'all':
        setShowList(list)
        break;

      case 'completed':
        setShowList(completedList)
        break;

      case 'uncompleted':
        setShowList(uncompletedList)
        break;
    
      default:
        break;
    }
  }

  // 添加待办事项
  const addTodoItem = () => {
    if (content.trim() !== '') {
      const item = {
        id: Math.random(),
        content,
        completed: false
      }
      setList([...list, item])
      setContent('')
      inputRef.current!.focus()
    } else return
  }

  const inputChange = (e: any) => {
    setContent(e.target.value)
  }

  // input回车
  const pressEnter = (e: any) => {
    e.keyCode === 13 && addTodoItem()
  }

  // 点击删除
  const clickDelete = (item:ItemType) => {
    const newList = list.filter(i => i.id !== item.id)
    setList(newList)
    setShowList(newList)
  }

  // 点击复选框勾选
  const checkChange = (item:ItemType,e:any)=>{
    item.completed = e.target.checked
    console.log('e.target.checked: ', e.target.checked);
    const arr = showList.filter(i => i.id!== item.id)
    console.log('current',current);
    // 如何实现勾选复选框切换完成状态，切换不同菜单项显示对应完成状态的数据？
  }

  return (
    <div className='list'>
      <div className='list-input'>
        <Input placeholder='请输入待办事项' ref={inputRef} value={content} onChange={inputChange} name={content} onPressEnter={pressEnter} />
        <Button type='primary' onClick={addTodoItem}>添加</Button>
      </div>
      <Menu
        mode="horizontal"
        items={items}
        selectedKeys={[current]}
        onClick={menuChange}
      >
      </Menu>
        <List
          itemLayout="horizontal"
          dataSource={showList}
          renderItem={item => (
            <List.Item
              key = {item.id}
              actions={[<a key="list-loadmore-delete" href='/' onClick={(e)=>{
                e.preventDefault()
                clickDelete(item)
              }}>删除</a>]}
            >
              <Checkbox onChange={(e)=>checkChange(item,e)}/>
              <List.Item.Meta title={item.content} style={{backgroundColor:item.completed?'#eaeaea':'#FFF'}}/>
            </List.Item>
          )}
        >
        </List>
    </div>
  )
}